/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.z100h.supplychain.sku.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.z100h.supplychain.sku.entity.Sku;
import com.z100h.supplychain.sku.service.SkuService;
import com.z100h.supplychain.statistics.entity.RealtimeResourceAmount;
import com.z100h.supplychain.statistics.service.StatRealtimeResourceService;
import com.z100h.supplychain.supplier.entity.Supplier;
import com.z100h.supplychain.supplier.service.SupplierService;

/**
 * 供应链产品管理Controller
 * @author madara
 * @version 2018-09-20
 */
@Controller
@RequestMapping(value = "${adminPath}/sku/sku")
public class SkuController extends BaseController {

	@Autowired
	private SkuService skuService;

	@Autowired
	private SupplierService supplierService;

	@Autowired
	private StatRealtimeResourceService statRealtimeResourceService;

	@ModelAttribute
	public Sku get(@RequestParam(required = false) String id) {
		Sku entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = skuService.get(id);
		}
		if (entity == null) {
			entity = new Sku();
		}
		return entity;
	}

	/**
	 * 产品模板列表页面
	 */
	@RequiresPermissions("sku:sku:list")
	@RequestMapping(value = { "list", "" })
	public String list() {
		return "supplychain/sku/skuList";
	}

	/**
	* 产品模板列表数据
	*/
	@ResponseBody
	@RequiresPermissions("sku:sku:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Sku sku, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Sku> page = skuService.findPage(new Page<Sku>(request, response), sku);
		return getBootstrapData(page);
	}

	/**
	 * sku下拉列表数据
	 * @param sku
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sku:sku:findSkuList")
	@RequestMapping(value = "findSkuList")
	public List<Sku> findSkuList(Sku sku, HttpServletRequest request, HttpServletResponse response, Model model) {
		// 查询同仓库下的sku
		sku.setDepartmentId(UserUtils.getUser().getOffice().getId());
		List<Sku> list = skuService.findList(sku);
		return list;
	}

	/**
	 * 查看，增加，编辑产品模板表单页面
	 */
	@RequiresPermissions(value = { "sku:sku:view", "sku:sku:add", "sku:sku:edit" }, logical = Logical.OR)
	@RequestMapping(value = "form")
	public String form(HttpServletRequest request, Sku sku, Model model) {
		model.addAttribute("sku", sku);
		if (StringUtils.isBlank(sku.getId())) {// 如果ID是空为添加
			model.addAttribute("isAdd", true);
		}

		/**
		 * 供应商列表
		 */
		Supplier supplier = new Supplier();
		User logUser = UserUtils.getUser();
		supplier.setCompanyId(logUser.getCompany().getId());// 根据公司查询
		List<Supplier> supplierList = supplierService.findList(supplier);
		request.setAttribute("supplierList", supplierList);

		return "supplychain/sku/skuForm";
	}

	/**
	 * 保存产品模板
	 */
	@RequiresPermissions(value = { "sku:sku:add", "sku:sku:edit" }, logical = Logical.OR)
	@RequestMapping(value = "save")
	@ResponseBody
	public Map<String, String> save(HttpServletRequest request, Sku sku, Model model,
			RedirectAttributes redirectAttributes) throws Exception {
		/*
		 * if (!beanValidator(model, sku)){ return form(request,sku, model); }
		 */
		Map<String, String> map = new HashMap<String, String>();
		// 新增或编辑表单保存
		try {
			skuService.save(sku);// 保存
			map.put("code", "0");
			map.put("message", "保存转库单成功");
		} catch (Exception e) {

			map.put("code", "1");
			map.put("message", "sku保存失败,已存在相同的sku");
			logger.error("SkuController is save.", e);
		}
		// addMessage(redirectAttributes, message);
		// return "redirect:"+Global.getAdminPath()+"/sku/sku/?repage";
		return map;
	}

	/**
	 * 删除产品模板
	 */
	@ResponseBody
	@RequiresPermissions("sku:sku:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Sku sku, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		skuService.delete(sku);
		j.setMsg("删除产品模板成功");
		return j;
	}

	/**
	 * 批量删除产品模板
	 */
	@ResponseBody
	@RequiresPermissions("sku:sku:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
			String idArray[] = ids.split(",");
			for (String id : idArray) {
				skuService.delete(skuService.get(id));
			}
			j.setMsg("删除产品模板成功");
		} catch (Exception e) {
			e.printStackTrace();
			j.setSuccess(false);
			if (e instanceof DataIntegrityViolationException) {
				j.setMsg("sku有关联，不允许删除");
			}
		}
		return j;
	}

	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("sku:sku:export")
	@RequestMapping(value = "export", method = RequestMethod.POST)
	public AjaxJson exportFile(Sku sku, HttpServletRequest request, HttpServletResponse response,
			RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
			String fileName = "产品模板" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
			Page<Sku> page = skuService.findPage(new Page<Sku>(request, response, -1), sku);
			new ExportExcel("产品模板", Sku.class).setDataList(page.getList()).write(response, fileName).dispose();
			j.setSuccess(true);
			j.setMsg("导出成功！");
			return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出产品模板记录失败！失败信息：" + e.getMessage());
		}
		return j;
	}

	/**
	 * 导入Excel数据
	
	 */
	@RequiresPermissions("sku:sku:import")
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Sku> list = ei.getDataList(Sku.class);
			for (Sku sku : list) {
				try {
					skuService.save(sku);
					successNum++;
				} catch (ConstraintViolationException ex) {
					failureNum++;
				} catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum > 0) {
				failureMsg.insert(0, "，失败 " + failureNum + " 条产品模板记录。");
			}
			addMessage(redirectAttributes, "已成功导入 " + successNum + " 条产品模板记录" + failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入产品模板失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/sku/sku/?repage";
	}

	/**
	 * 下载导入产品模板数据模板
	 */
	@RequiresPermissions("sku:sku:import")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "产品模板数据导入模板.xlsx";
			List<Sku> list = Lists.newArrayList();
			new ExportExcel("产品模板数据", Sku.class, 1).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/sku/sku/?repage";
	}

	/**
	 * sku弹窗页面
	 * @return
	 */
	@RequestMapping(value = { "pop" })
	public String pop() {
		return "supplychain/sku/pop";
	}

	@RequestMapping(value = { "pop2" })
	public String pop2() {
		return "supplychain/sku/pop2";
	}

	/**
	 * 
	 * 实时资源汇总
	 * 
	 * @return
	 * @author: Fyh - 1009173473@qq.com 
	 * @date: Created on 2020年7月7日 下午3:06:33
	 */
	@ResponseBody
	@RequestMapping(value = "findRealtimeResourceAmount")
	public Map<String, Object> findRealtimeResourceAmount(RealtimeResourceAmount realtimeResourceAmount,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<RealtimeResourceAmount> page = statRealtimeResourceService.findRealtimeResourceAmount(
				realtimeResourceAmount, new Page<RealtimeResourceAmount>(request, response));
		return getBootstrapData(page);
	}

}